package cc.shacocloud.mirage.core.bind.support;

import cc.shacocloud.mirage.core.Condition;
import cc.shacocloud.mirage.core.ConditionContext;
import cc.shacocloud.mirage.core.bind.ConditionalOnClass;
import cc.shacocloud.mirage.utils.ClassUtil;
import cc.shacocloud.mirage.utils.annotation.AnnotatedElementMetadata;
import org.jetbrains.annotations.NotNull;

import static cc.shacocloud.mirage.core.bind.ConditionalOnClass.Mode;

/**
 * 当存在指定类加载
 *
 * @author 思追(shaco)
 * @see ConditionalOnClass
 */
public class OnClassCondition implements Condition {
    
    @Override
    public boolean matches(@NotNull ConditionContext context,
                           @NotNull AnnotatedElementMetadata annotatedElementMetadata) {
        ConditionalOnClass conditionalOnClass = annotatedElementMetadata.getAnnotation(ConditionalOnClass.class);
        assert conditionalOnClass != null;
        
        final ClassLoader classLoader = context.getClassLoader();
        
        String[] value = conditionalOnClass.value();
        Mode mode = conditionalOnClass.mode();
        
        // 满足任意一个
        if (Mode.ANY.equals(mode)) {
            for (String className : value) {
                if (ClassUtil.isPresent(className, classLoader)) {
                    return true;
                }
            }
            
            return false;
        }
        
        // 满足所有
        for (String className : value) {
            if (!ClassUtil.isPresent(className, classLoader)) {
                return false;
            }
        }
        return true;
    }
}
